package edu.cth.speedapp.old;

import edu.cth.speedapp.CameraPreview;
import edu.cth.speedapp.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.Button;

import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Size;

import android.widget.TextView;
/* Import ZBar Class files */
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;


@SuppressLint({ "ParserError", "ParserError", "ParserError", "ParserError" })
public class CameraQRActivity extends Activity
{
	public static final String QR_CODE_EXTRA = "com.example.mycameratest.qrCode";
	
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;

    TextView scanText;
    Button scanButton;
    Button okButton;

    ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;
    
    private Activity thisActivity;

    static {
        System.loadLibrary("iconv");
    } 

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_qr_camera);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        thisActivity = this;
       
        
        scanText = (TextView)findViewById(R.id.scanText);

        scanButton = (Button)findViewById(R.id.ScanButton);
        
        okButton = (Button) findViewById(R.id.ConfirmQrButton);
        scanButton.setVisibility(View.INVISIBLE);
        okButton.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	autoFocusHandler = new Handler();
    	
    	 mCamera = getCameraInstance();
         
         // Instance barcode scanner //
         scanner = new ImageScanner();
         scanner.setConfig(0, Config.X_DENSITY, 3);
         scanner.setConfig(0, Config.Y_DENSITY, 3);
         
         mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
         FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
         preview.removeAllViews();
         preview.addView(mPreview);
         
         
         
         
         scanButton.setOnClickListener(new OnClickListener() {
                 public void onClick(View v) {
                     if (barcodeScanned) {
                         barcodeScanned = false;
                         scanText.setText("Scanning...");
                         mCamera.setPreviewCallback(previewCb);
                         mCamera.startPreview();
                         previewing = true;
                         mCamera.autoFocus(autoFocusCB);
                         v.setVisibility(View.INVISIBLE);
                     }
                 }
             });
    	
    	
    }
    
    public void onPause() {
        super.onPause();
        releaseCamera();
        
    }

    /** A safe way to get an instance of the Camera object. */
    @SuppressLint("ParserError")
	public static Camera getCameraInstance(){
        Camera c = null;
       try{
        c = Camera.open();
      }catch(Exception e){
    	  
      }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }
    
    public void confirmQRClick(View v){
    	this.finish();
    }
    

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {   	
    	
            @SuppressLint("ParserError")
			public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);
                
                if (result != 0) {
                    previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();
                    
                    SymbolSet syms = scanner.getResults();
                    for (Symbol sym : syms) {
                        scanText.setText("QR scanned: " + sym.getData());
                        barcodeScanned = true;
                        
                        Intent intent = new Intent();
                        intent.putExtra(QR_CODE_EXTRA, sym.getData());
                        thisActivity.setResult(RESULT_OK, intent);
                        
                        scanButton.setVisibility(View.VISIBLE);
                        okButton.setVisibility(View.VISIBLE);
                    }
                }
            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, 1000);
            }
        };
        
        
        
        
        
}